package com.aigao.golf.common.shiro

import com.aigao.golf.common.CommonUser
import com.aigao.golf.management.user.model.GlUser
import com.aigao.golf.market.customer.model.MkCustomer
import com.aigao.golf.market.customer.service.MkCustomerService
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.AuthenticationInfo
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.authc.SimpleAuthenticationInfo
import org.apache.shiro.authz.Permission
import org.apache.shiro.subject.PrincipalCollection
import org.slf4j.LoggerFactory

import javax.annotation.PostConstruct

class ShiroRealmPwd : BaseAuthRealm() {


    /**
     * 登录验证
     * @throws AuthenticationException
     */
    @Throws(AuthenticationException::class)
    override fun doGetAuthenticationInfo(authToken: AuthenticationToken): AuthenticationInfo? {
        val token = authToken as MyUPToken
        when (token.getChannel()) {
            MyUPToken.MK_LITE_APP -> {
                var mkCustomer:MkCustomer? = MkCustomer()
                mkCustomer?.phone = token.username
                mkCustomer?.let {
                    mkCustomer = mkCustomerService.selectOne(it)
                }
                if (mkCustomer != null) {
                    log.debug("login :" + MkCustomer::class.java.name + ">>>" + token.username)
                    this.setSession(mkCustomer)
                    return SimpleAuthenticationInfo(mkCustomer, mkCustomer, MyUPToken.MK_LITE_APP.toString() + "")
                } else {
                    log.debug("login fail :" + MkCustomer::class.java.name + ">>>" + token.username)
                    return null
                }
            }
            MyUPToken.GL_WEB -> {
                var glUser:GlUser? = GlUser()
                glUser?.username = token.username
                glUser?.let {
                    glUser = glUserService.selectOne(it)
                }
                log.debug("login :" + GlUser::class.java.name + ">>>" + token.username)
                this.setSession(glUser)
                return SimpleAuthenticationInfo(glUser, glUser, MyUPToken.GL_WEB.toString() + "")
            }
            else -> return null
        }
    }

    @PostConstruct
    override fun initCredentialsMatcher() {
        this.credentialsMatcher = UserCredentialsMatcherPwd()
    }

    private fun setSession(user: CommonUser?) {
        val currentUser = SecurityUtils.getSubject()
        if (currentUser != null) {
            val session = currentUser.session
            session?.setAttribute("user", user)
        }
    }

    companion object {
        val log = LoggerFactory.getLogger(ShiroRealmPwd::class.java)
    }


}
